import pandas as pd

task ="""Task for Distribution System Power Restoration:
Objective: Determine the optimal set of switches to open/close(Always keep faulted lines isolated by setting status=0), restoring maximum load demand and minimizing switch operations (reducing total switch actions)while maintaining a radial topology without overloads or voltage violations.

The input consists of a node load table (Bus | Pd | Qd), a line impedance table (From | To | Impedance | Status), a power source capacity table (Bus | Capacity), and a fault location.
In the line impedance table, status=1 indicates that this line was in a closed state before the fault occurred, status=0 indicates that this line was in an open state before the fault occurred, and status=-1 indicates that this line is not equipped with a switch and always be considered as closed.

Output Requirements: List switches with changed status using following json format
{
 "success":true/false,
 "action":[List switches with changed status using tuple(From,To,Status). For example, to open switch between 123 and 234 can be expressed as (123,234,0)],
 "supplied_loads":{
	List all loads supplied by each power source with bus as field name. For unsupplied loads, put them in "offline" field. For example, "345":[55,66] expressed power source at bus 345 supplies power to loads at 55 and 66. "offline":[77,88] expressed loads at 77 and 88 are unsupplied.
 }
}

Key Analysis Steps to Perform:
1.Fault Isolation: Change status of lines to isolated lines tagged by active faults
2.Feasibility Check: Verify if VSources can support restored loads
3.Radial Validation: The network shall not contain any meshed loops (acyclic condition).Each power source and its supplied nodes constitute an independent power supply zone.For any supply zone, the topology must satisfy:Number of closed branches = Number of nodes - 1.
4.Capacity Check: Ensure that the total load supplied by each power source does not exceed the capacity of that power source.

Terminate if:
No feasible radial configuration meets voltage constraints
All candidate solutions overload sources

Set "success" when find feasible configuration. If terminated, set "success" to false.

"""

# 读取Excel文件
df_load = pd.read_excel(
    "data\\all_load_node_mapped.xlsx"
)
df_capacity = pd.read_excel("data\\capacity.xlsx")
df_branch = pd.read_excel(
    "data\\运行方式1-branch_reordered.xlsx"
)

# 首先读取branch
# 选择需要的列
selected_columns = ['F-Node-map','T-Node-map','r','x','SwitchState']
df_selected = df_branch[selected_columns]
branch_details = []
# 添加表头
header = "line impedance table is as follows: From | To | Impedance | Status"
branch_details.append(header)
# 添加每一行数据
for index, row in df_selected.iterrows():
    from_node = int(row['F-Node-map'])
    to_node = int(row['T-Node-map'])
    impedance = f"{row['r']:.3f}+{row['x']:.3f}j" if row['r'] > 0 and row['x'] > 0 else "0"
    status = int(row['SwitchState'])
    branch_details.append(f"{from_node}|{to_node}|{impedance}|{status}")
# 将branch_details转换为字符串
branch_str = "\n".join(branch_details)
# print("Branch Details:")
# print(branch_str)

# 读取负荷数据
selected_load_columns = ['Node-map', 'P', 'Q']
df_load_selected = df_load[selected_load_columns]
load_details = []
# 添加表头
load_header = "node load table is as follows: Bus|Pd|Qd"
load_details.append(load_header)
# 添加每一行数据
for index, row in df_load_selected.iterrows():
    bus = int(row['Node-map'])
    p = row['P'] if row['P']!=0 else 0
    q = row['Q'] if row['Q']!=0 else 0
    load_details.append(f"{bus}|{p}|{q}")
load_str = "\n".join(load_details)
# print("Load Details:")
# print(load_str)

# 读取容量数据
selected_capacity_columns = ['id-map', 'capacity']
df_capacity_selected = df_capacity[selected_capacity_columns]
capacity_details = []
# 添加表头
capacity_header = "power source capacity table is as follows: Bus | Capacity"
capacity_details.append(capacity_header)
# 添加每一行数据
for index, row in df_capacity_selected.iterrows():
    bus = int(row['id-map'])
    capacity = row['capacity'] if row['capacity']!=0 else 0
    capacity_details.append(f"{bus}|{capacity}")
capacity_str = "\n".join(capacity_details)
# print("Capacity Details:")
# print(capacity_str)

sample_str =task + "\n\n" + branch_str + "\n\n" + load_str + "\n\n" + capacity_str
# 将生成的字符串写入sample_auto.txt
with open('sample_auto.txt', 'w') as f:
    f.write(sample_str)
